<?php

namespace Kangcg\Application\Base\Trait;

use Kangcg\Application\Trait\ExceptionError;

trait ExtendTrait
{
    protected array|null $extend = null;

    /**
     * 伪多继承
     * @return array   [ '扩展名称' => 扩展实例或者其他]
     * [
     * 'redis' => new \Redis,
     * 'redis' => \Redis::class,
     * 'redis' => [
     * 'class' => \Redis::class
     * 127.0.0.1 //其他参数
     * 6399 //其他参数
     * ],
     * 'redis' => [
     * \Redis::class,
     * 127.0.0.1 //其他参数
     * 6399 //其他参数
     * ],
     * ]
     *
     *
     */
    public function extends(): array
    {
        return [];
    }

    /**
     * @param string $name
     * @return Object|null
     */
    public function getExtend($name)
    {
        $this->ensureExtends();
        return $this->_extends[$name] ?? null;
    }

    protected function ensureExtends()
    {
        if ($this->_extends === null) {
            $this->_extends = [];
            foreach ($this->extends() as $name => $extend) {
                $this->attachExtendInternal($name, $extend);
            }
        }
    }

    /**
     * @param $name
     * @param $arguments
     * @return mixed
     * @throws ExceptionError
     */
    public function __call($name, $arguments)
    {
        $arguments[] = $this;
        $this->ensureExtends();
        foreach ($this->_extends as $extends) {
            if (method_exists($extends, $name)) {
                return call_user_func_array([$extends, $name], $arguments);
            }
        }

        throw new \Exception('当前类方法不存在:' . $name);
    }
}
